package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.base.domain.User;
import cn.wolfcode.car.base.service.IUserService;
import cn.wolfcode.car.business.domain.*;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.*;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private IBusinessStatementService businessStatementService;
    @Autowired
    private IAppointmentService appointmentService;
    @Autowired
    private IServiceItemService serviceItemService;
    @Autowired
    private IUserService userService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private TaskService taskService;

    //分页+过滤
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(),qo.getPageSize());
        List<CarPackageAudit> carPackageAudits=carPackageAuditMapper.selectForList(qo);
        //在这将查询到的审核对象（实体类）进一步补充属性以符合页面显示要求
        for (CarPackageAudit carPackageAudit:carPackageAudits) {
            ServiceItem serviceItem = serviceItemService.get(carPackageAudit.getServiceItemId());
            carPackageAudit.setServiceItem(serviceItem);
            User auditor = userService.get(carPackageAudit.getAuditorId());
            carPackageAudit.setAuditor(auditor);
        }
        return new TablePageInfo<>(carPackageAudits);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }

    //结算单添加
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(String ids) {

    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    /**
     * 审批:其实就是通过判断审批的结果，对审核流程记录单和服务单项做一些状态修改。
     *  结合activiti工作流的整个过程来编写我们的业务流程逻辑
     * @param id
     * @param auditStatus
     */
    public void audit(Long id, int auditStatus) {
        //1、获取对应的审批的流程审核单
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        //1.1设置流程审核记录表info中的信息+审核时间
        String info = carPackageAudit.getInfo();
        User user = userService.get(carPackageAudit.getAuditorId());//获取当前节点的角色的某个负责人
        info+=user.getLoginName()+"签名审核"+new Date();
        carPackageAuditMapper.updateInfo(carPackageAudit.getId(),info);
        carPackageAuditMapper.updateAuditTime(carPackageAudit.getId(),new Date());
        //1.1当前任务节点（注意设置流程变量要推动activiti流程的执行）
        Task task = taskService.createTaskQuery()
                .processInstanceId(carPackageAudit.getInstanceId())
                .singleResult();
        //可以给当前任务设置添加流程变量(值为传过来的)
        taskService.setVariable(task.getId(),"auditStatus",auditStatus);
        //还可以给当前任务添加审批信息
        taskService.addComment(task.getId(),carPackageAudit.getInstanceId(),"店长同意！");//需要当前任务所在流程实例
        taskService.complete(task.getId());

        //2、审批通过
        if(auditStatus ==CarPackageAudit.STATUS_PASS){
            //1.2判断下一个节点是否存在（activiti流程还在执行吗）
            Task nextTask =taskService.createTaskQuery()
                                        .processInstanceId(carPackageAudit.getInstanceId())
                                        .singleResult();
            if(nextTask==null){//不存在，修改服务单项状态+审核记录单状态
                serviceItemService.updateStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
                carPackageAuditMapper.updateStatus(carPackageAudit.getId(),CarPackageAudit.STATUS_PASS);
                //最后审核时间
            }else {//存在，就修改当前流程审核记录表中的当前任务的负责人
                String auditorId = nextTask.getAssignee();//***先获取这个任务的负责人（id）
                carPackageAuditMapper.updateAuditorId(carPackageAudit.getId(),Long.valueOf(auditorId));
            }

        }else {
            //3、审批拒绝
            //将服务单项状态+审核状态+删除该流程实例
            serviceItemService.updateStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
            carPackageAuditMapper.updateStatus(id,CarPackageAudit.STATUS_REJECT);
            //根据当前的实例id进行删除
//            runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId(),"店长拒绝审批！");
        }


    }

}
